package com.zjdiepu.www.biz.third.net;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.ExpressStatus;
import com.zjdiepu.www.base.enums.type.HttpRequestErrorType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.lang.HttpClientException;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.consts.ThirdService;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.commpent.HttpClient;
import com.zjdiepu.www.config.AliServiceProperty;
import com.zjdiepu.www.ibiz.third.IAliDeliverInfoDetailService;
import com.zjdiepu.www.ibiz.third.IAliDeliverInfoService;
import com.zjdiepu.www.ibiz.third.net.IDeliverService;
import com.zjdiepu.www.model.third.dto.AliDeliverInfo;
import com.zjdiepu.www.model.third.dto.AliDeliverInfoDetail;
import com.zjdiepu.www.model.third.ext.AliDeliverInfoDetailExt;
import com.zjdiepu.www.model.third.request.ali.AliDeliverRequest;
import com.zjdiepu.www.model.third.response.ali.AliDeliverResponse;
import com.zjdiepu.www.model.third.response.ali.AliDeliverResponseForShow;
import com.zjdiepu.www.model.third.response.ali.DeliverShowApiResBody;
import com.zjdiepu.www.model.third.response.ali.DeliverTrace;
import com.zjdiepu.www.util.ExceptionHelper;
/**
 * 项目名称：dpqc-parent-manager-party <br/> 
 * 类名称：AliDeliverServiceImpl <br/>  
 * 类描述： 物流单号的跟踪信息<br/>    
 * 创建人：xiongxiaotun <br/> 
 * 创建时间：2017年4月18日 下午1:35:48  <br/>   
 * 修改人：xiongxiaotun <br/> 
 * 修改时间：2017年4月18日 下午1:35:48   <br/>  
 * 修改备注：    <br/> 
 * @version V1.0   <br/>
 */
@Service
public class AliDeliverServiceImpl extends BaseService implements IDeliverService<AliDeliverRequest, AliDeliverResponseForShow> {
	@Resource
	protected HttpClient httpClient;
	@Resource
	private AliServiceProperty aliServiceProperty;
	@Autowired
	private IAliDeliverInfoDetailService aliDeliverInfoDetailService;
	@Autowired
	private IAliDeliverInfoService aliDeliverInfoService;

	@Override
	public AliDeliverResponseForShow saveExpInfo(String nu, String com) throws SocketTimeoutException, HttpClientException {
		if (StringUtils.isBlank(nu)) {
			ExceptionHelper.thow(HttpRequestErrorType.REQUEST_API_BUSSINESS_IS_EMPTY.getCode(), "运单号不存在");
		}
		AliDeliverResponseForShow aliDeliverResponseForShow = new AliDeliverResponseForShow();
		List<AliDeliverInfoDetail> aliDeliverInfoDetails = new ArrayList<AliDeliverInfoDetail>();
		
		AliDeliverInfo aliDeliverInfoOld = aliDeliverInfoService.selectByNu(nu);
		if(!checkIfNeedQuery(aliDeliverInfoOld)){ //不需要重新查询
			AliDeliverInfoDetailExt aliDeliverInfoDetailExt = new AliDeliverInfoDetailExt();
			aliDeliverInfoDetailExt.setBaseWhere();
			aliDeliverInfoDetailExt.withOutPage();
			aliDeliverInfoDetailExt.setDeliverInfoId(aliDeliverInfoOld.getId());
			aliDeliverInfoDetailExt.setOrderSql("`TIME` ASC");
			aliDeliverInfoDetails = aliDeliverInfoDetailService.selectByExt(aliDeliverInfoDetailExt);
			
			aliDeliverResponseForShow.setSuccess(ExpressStatus.ALREADY_SIGN.getCode().equals(aliDeliverInfoOld.getStatus().toString()));
		} else {
			Map<String, String> paramMap = getEmptyParamMap();
			paramMap.put("com", StringUtils.isBlank(com)?"auto":com);
			paramMap.put("nu", nu);
			String responseJson = httpClient.get(ThirdService.ALI_DELIVER, paramMap, getAliCommonHeaderMap(aliServiceProperty.getAppCode()));
			logger.debug(responseJson);
			if (StringUtils.isBlank(responseJson)) {
				ExceptionHelper.thow(HttpRequestErrorType.RESPONSE_IS_EMPTY);
			}
			AliDeliverResponse response = JSON.parseObject(responseJson, AliDeliverResponse.class);
			if (null == response || !SystemConsts.RETURN_SUCCESS_CODE.equals(response.getShowapiResCode())) {
				ExceptionHelper.thow(HttpRequestErrorType.REQUEST_API_ERROR);
			}
			DeliverShowApiResBody showapiResBody = response.getShowapiResBody();
			if (null == showapiResBody || !SystemConsts.RETURN_SUCCESS_CODE.equals(showapiResBody.getRetCode())) {
				ExceptionHelper.thow(HttpRequestErrorType.REQUEST_API_BUSSINESS_ERROR);
			}
			
	
			AliDeliverInfo aliDeliverInfo = new AliDeliverInfo();
			BeanUtils.copyProperties(showapiResBody, aliDeliverInfo);
			aliDeliverInfoService.saveUpdateAndDelete(aliDeliverInfo, OperateType.add);
	
			Boolean flag = showapiResBody.getFlag();
			if (null != flag && flag) {
				List<DeliverTrace> data = showapiResBody.getData();
				if (CollectionUtils.isNotEmpty(data)) {
					int size = data.size();
					for (int i = size - 1; i >= 0; i--) {
						DeliverTrace deliverTrace = data.get(i);
						AliDeliverInfoDetail aliDeliverInfoDetail = new AliDeliverInfoDetail();
						BeanUtils.copyProperties(deliverTrace, aliDeliverInfoDetail);
						aliDeliverInfoDetail.setId(UUIDFactory.getUUID());
						aliDeliverInfoDetail.setDpStatus(DpStatus.NORMAL.getCode());
						aliDeliverInfoDetail.setDeliverInfoId(aliDeliverInfo.getId());
						aliDeliverInfoDetails.add(aliDeliverInfoDetail);
					}
				}
				
				if(CollectionUtils.isNotEmpty(aliDeliverInfoDetails)) {
					if(null != aliDeliverInfoOld) {
						aliDeliverInfoService.deleteByNu(showapiResBody.getMailNo());
						aliDeliverInfoDetailService.deleteByInfoId(aliDeliverInfoOld.getId());
					}
					aliDeliverInfoDetailService.insertBatch(aliDeliverInfoDetails);
				}
			}
			aliDeliverResponseForShow.setSuccess(ExpressStatus.ALREADY_SIGN.getCode().equals(aliDeliverInfo.getStatus().toString()));
		}
		aliDeliverResponseForShow.setAliDeliverInfoDetails(aliDeliverInfoDetails);
		return aliDeliverResponseForShow;
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: checkIfNeedQuery  <br/>
	 * @Description: 检查是否需要重新查询快递单号  <br/>
	 * @return 
	 * @version V1.0  <br/>
	 */
	private boolean checkIfNeedQuery(AliDeliverInfo aliDeliverInfoOld){
		if(null == aliDeliverInfoOld) { //还没有存储运单
			return true;
		}
		Integer oldStatus = aliDeliverInfoOld.getStatus();
		if(null == oldStatus) { //运单状态缺失
			return true;
		}
		String oldStatusStr = oldStatus.toString();
		if(!ExpressStatus.ALREADY_SIGN.getCode().equals(oldStatusStr) 
				&& !ExpressStatus.MAIL_RETURNED.getCode().equals(oldStatusStr) 
				&& !ExpressStatus.INVALID_SINGLE.getCode().equals(oldStatusStr)) { //没有终结的订单需要再次查询
			return true;
		}
		AliDeliverInfoDetailExt aliDeliverInfoDetailExt = new AliDeliverInfoDetailExt();
		aliDeliverInfoDetailExt.setBaseWhere();
		aliDeliverInfoDetailExt.setDeliverInfoId(aliDeliverInfoOld.getId());
		int details = aliDeliverInfoDetailService.countByExt(aliDeliverInfoDetailExt);
		if(details < 1) { //没有运转信息
			return true;
		}
		return false;
	}
}

